package com.biboheart.adapter.express.support;

import com.biboheart.adapter.express.operation.Logical;

import java.util.HashMap;
import java.util.Map;

public class GenericLogicalService implements ConfigurableLogicalService{
    private final Logicals logicals = new Logicals();

    @Override
    public void addLogical(String character, Logical logical) {
        logicals.add(character, logical);
    }

    @Override
    public void removeLogical(String character) {
        logicals.remove(character);
    }

    @Override
    public Boolean execute(String character, Object left, Object right) {
        Logical logical = logicals.getLogical(character);
        if (null == logical) {
            return false;
        }
        return logical.calc(left, right);
    }

    @Override
    public Boolean execute(String character, Boolean source) {
        Logical logical = logicals.getLogical(character);
        if (null == logical) {
            return false;
        }
        return logical.calc(source);
    }

    private static class Logicals {
        private final Map<String, Logical> logicalHash = new HashMap<>();

        public void add(String name, Logical logical) {
            logicalHash.put(name, logical);
        }

        public void remove(String name) {
            logicalHash.remove(name);
        }

        public Logical getLogical(String name) {
            if ("".equals(name) || null == name) {
                return null;
            }
            return logicalHash.get(name);
        }
    }
}
